<template>
  <div class="event-report-page page">
    <nav-bar title="事件上报" theme="white" message></nav-bar>
    <div class="event-report-main page-main" style="margin-top: 44px">
      <div class="event-map" id="container" @click="mapClick"></div>
      <div class="event-map-bottom">
        <div class="btns">
          <van-button size="small" type="default" @click="cancelMap">取消</van-button>
          <van-button size="small" type="info" @click="confirmMap">确定</van-button>
        </div>
        <van-search
          id="searchInput"
          v-model="searchVal"
          placeholder="搜索地点"
          @input="handleInput"
          @clear="handleClear"
        />
        <ul class="res-list">
          <li class="res-item" v-for="(item, index) in adList" :key="index" @click="adClick(item)">
            {{ item.name }}
            <p class="address-text" v-show="item.address">{{ item.address }}</p>
            <img
              v-show="curId == item.id"
              class="address-selected"
              src="@/assets/images/event/address-selected.png"
              alt=""
            />
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import mapPlugin from '@/libs/mapPlugin'
import General from '@/api/general'
export default {
  data() {
    return {
      map: null,
      center: [],
      markers: [],
      overlayGroup: null,
      searchVal: '',
      adList: [],
      longitude: '',
      latitude: '',
      keyword: '',
      cityCode: '',
      adName: '',
      curId: '',
      gridScope: null,
      gridScopeArr: [],
      validArr: []
    }
  },
  computed: {
    ...mapState({
      user: state => state.userInfo
    })
  },
  mounted() {
    this.map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 16
    })
    this.init()
    this.getGridScope()
    this.map.on('click', e => {
      this.longitude = e.lnglat.lng
      this.latitude = e.lnglat.lat
      this.mapClick()
    })
  },
  methods: {
    init() {
      mapPlugin.geolocation(res => {
        // 获取当前位置
        this.longitude = res.position.lng
        this.latitude = res.position.lat
        this.lnglatChange()
        mapPlugin.geocoder(res.position, async res2 => {
          // 查询经纬度信息
          this.cityCode = res2.regeocode.addressComponent.citycode
          this.keyword = res2.regeocode.addressComponent.businessAreas[0].name
          this.placeSearch(this.keyword)
        })
      })
    },
    placeSearch(keyword) {
      // 地点搜索
      mapPlugin.placeSearch(this.cityCode, keyword, async res => {
        this.adList = res.poiList.pois
        this.adName = this.adList[0].name
        this.longitude = this.adList[0].location.lng
        this.latitude = this.adList[0].location.lat
        this.curId = this.adList[0].id
        this.lnglatChange()
      })
    },
    handleInput(val) {
      if (val) {
        this.placeSearch(val)
      } else {
        this.init()
      }
    },
    handleClear(e) {
      this.init()
    },
    adClick(item) {
      // 点击搜索列表
      this.longitude = item.location.lng
      this.latitude = item.location.lat
      this.adName = item.name
      this.curId = item.id
      this.lnglatChange()
    },
    mapClick() {
      // 点击地图
      this.center = [this.longitude, this.latitude]
      mapPlugin.geocoder(this.center, async res => {
        this.keyword = res.regeocode.formattedAddress
        this.placeSearch(this.keyword)
      })
      this.map.setCenter(this.center)
    },
    lnglatChange() {
      this.center = [this.longitude, this.latitude]
      this.setMarker()
      this.map.setCenter(this.center)
      this.map.setZoom(16)
    },
    setMarker() {
      // 设置标注点
      const marker = new AMap.Marker({
        position: new AMap.LngLat(this.longitude.toFixed(8), this.latitude.toFixed(8)),
        anchor: 'bottom-center'
      })
      this.markers.push(marker)
      if (this.markers.length) {
        this.overlayGroup = new AMap.OverlayGroup(this.markers)
        this.map.add(this.overlayGroup)
      }
    },
    cancelMap() {
      // 取消
      this.$router.push('/event/report')
    },
    confirmMap() {
      this.validArr = []
      this.gridScopeArr.forEach(scope => {
        this.validArr.push(AMap.GeometryUtil.isPointInRing([this.longitude, this.latitude], scope))
      })
      const isGrid = this.validArr.some(v => v === true)
      // const isGrid = AMap.GeometryUtil.isPointInRing([this.longitude, this.latitude], this.gridScope)
      if (!isGrid) {
        this.$toast('该事件不在网格范围内')
      }
      // 确定
      const paramsData = {
        longitude: this.longitude,
        latitude: this.latitude,
        adName: this.adName
      }
      this.$router.push({
        name: 'event-report',
        params: { mapData: paramsData }
      })
    },
    getGridScope() {
      // 获取网格范围
      General.Region.getGridScopes({ code: this.user.gridCode }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.gridScopeArr = []
          data.forEach(item => {
            this.gridScopeArr.push(JSON.parse(JSON.parse(item)[0]))
          })
          console.log(this.gridScopeArr)
          // console.log(JSON.parse(data))
          // this.gridScope = JSON.parse(JSON.parse(data)[0])
          // console.log(this.gridScope)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@/assets/style/event/map.less';
</style>
